<template>
  <d2-container>
  <div class="app-container">
    <el-container >
      <el-main class="theme-front-color">
        <!-- <el-row>
          <div class="search-area">
            <el-form label-position="right" :model="dataForm" :inline="true">
              <div style="font-size:15px;display:inline-block; float:left;">
                <el-form-item label="日期" label-width="40px">
                  <el-date-picker
                    v-model="dataForm.date"
                    placeholder="时间范围"
                    style="width: 350px;"
                    class="filter-item"
                    size="mini"
                    :type="dataForm.dateType"
                    suffix-icon="el-icon-date"
                    clearable
                    @keyup.enter.native="getAlarmDataList"
                  >
                  </el-date-picker>
                </el-form-item>
              </div>
              <div style="display:inline-block; float:right;">
                <el-form-item>
                  <el-button
                    class="filter-item"
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="getAlarmDataList"
                  >查询</el-button>
                </el-form-item>
              </div>
            </el-form>
          </div>
        </el-row> -->
        <div style="">
          <el-row>
            <el-col :span="4">
                <div class="theme-front-color"><span class="signLine"></span>告警详细信息</div>
            </el-col>
            <!--<el-col :span="4">-->
              <!--<span>采集分类:{{}}</span>-->
            <!--</el-col>-->
            <!--<el-col :span="4">-->
              <!--<span>告警上限: {{businessChart.up}}</span>-->
            <!--</el-col>-->
            <!--<el-col :span="4">-->
              <!--<span>告警下限: {{businessChart.down}}</span>-->
            <!--</el-col>-->
          </el-row>
          <el-row :gutter="10">
            <el-col :span="24">
              <!--<div id="businessAreaChart" class="busi-chart" :style="'height:'+chartHeight/2+'px;'"></div>-->
              <el-table
                :data="businessChart.info"
                border
                ref="alarmTable"
                row-key="alarmId"
                v-loading="dataListLoading1"
                highlight-current-row
                style="width: 100%; height: 200px;overflow:auto;"
              >
                <el-table-column
                  prop="meterCode"
                  header-align="center"
                  align="center"
                  label="设备编码"
                ></el-table-column>
                <el-table-column
                  prop="collectTypeName"
                  header-align="center"
                  align="center"
                  label="采集项"
                ></el-table-column>
                <el-table-column
                  prop="ctime"
                  header-align="center"
                  align="center"
                  label="采集时间"
                ></el-table-column>
                <el-table-column
                  prop="oval"
                  header-align="center"
                  align="center"
                  label="采集值"
                ></el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </div>
        <div style="margin-top:20px;">
          <div class="theme-front-color"><span class="signLine"></span>告警列表</div>
          <el-table
            :data="alarmDataList"
            border
            ref="alarmTable"
            row-key="alarmId"
            :height="chartHeight/2"
            v-loading="dataListLoading"
            highlight-current-row
            @row-click="clickRow"
            style="width: 100%; overflow:visible;"
          >
            <el-table-column
              prop="meterName"
              header-align="center"
              align="center"
              label="设备"
            ></el-table-column>
            <el-table-column
              prop="quotaName"
              header-align="center"
              align="center"
              label="指标"
            ></el-table-column>
             <el-table-column
              prop="createTime"
              header-align="center"
              align="center"
              label="时间"
            ></el-table-column>
          </el-table>
          <el-pagination
            class="mt-4"
            @size-change="sizeChangeHandle"
            @current-change="currentChangeHandle"
            :current-page="page.page_no"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="page.page_size"
            :total="page.total"
            layout="total, sizes, prev, pager, next, jumper">
          </el-pagination>
        </div>
      </el-main>
    </el-container>
  </div>
  </d2-container>
</template>

<script>
import * as Util from "@/utils";
import * as Echarts from 'echarts'
import Config from "@/utils/config"
import Minix from '../power/mixin'
export default {
  name: "voltage",
  mixins:[Minix],
  data() {
    return {
      Config:Config,
      dataListLoading: false,
      dataListLoading1: false,
      dataForm: {
        date:[new Date((new Date()).getTime()-1000*24*3600),new Date()],
        dateType:'datetimerange',
        energyType:''
      },
      page: {
        page: 1,
        total: 0,
        size: 10
      },
      alarmDataList:[],
      businessChart:{
          chart:"",
          x:['1F','2F','3F','4F','5F','6F','7F','8F','9F','10F','11F','12F','14F','13F','15F','16F','17F','18F','19F','20F','21F','22F','23F'],
          y:[0,10240,102400,1048576,10485760],
          data:[9,7,8,5,4,6,8,9,7,8,5,4,6,8,9,7,8,5,4,6,8,3,4],
          down:9,
          up:100,
          title:"用能情况",
          info:[]
      },
      color:['#708DE5','#2BD597', '#F6AD35'],
    };
  },
  computed: {
    containerHeight() {
      return Util.getClientHeight() - 143;
    },
    chartHeight(){
       return Util.getClientHeight() - 285;
    }
  },
  created() {
    // this.dataForm.dateType=Config.searchDate[0].date;
    //this.queryStatic("meterType");
    this.getAlarmDataList();
  },
  methods: {
     // 获取区域树
    getBuildInfoList() {
      this.$api.okhttp({
        url: this.$http.adornUrl("/ecs/ecsbuildinginfo/select"),
        method: "get",
        params: this.$http.adornParams({
          'page': 1,
          'limit': 10000,
          'key': '',
          customerId: this.$util.cookies.get("customer_id"),
          projectid:this.$util.cookies.get("cuuren_projectId")
        })
      }).then((data) => {
        if (data && data.code === 0) {
          this.dataBuildingList = Util.treeDataTranslate(
            data.menuList,
            "buildingId",
            "parentBuildingId"
          );
        } else {
          this.dataBuildingList = [];
        }
      });
    },
    exoprtData(){
      // 导出数据
      let header=['序号','区域','分类','本期用能','同期用能','环期用能','同比比率','环比比率','时间']
      let props=['index','buildName','energyTypeName','bqVal','tqVal','hqVal','tbPercent','hbPercent','date']
      let fileName=`区域用${ this.meterTypeList.find(item=>item.paramKey==this.dataForm.energyType).paramValue}统计`
      this.export2Excel(header,props,fileName,this.alarmDataList)
    },
    export2Excel (tH, fi, fiNa, dataList) {
      var tHeader = tH
      var filterVal = fi
      var fileName = fiNa
      require.ensure([], () => {
        const {export_json_to_excel} = require('@/utils/Export2Excel.js')
        const list = dataList
        const data = this.formatJson(filterVal, list)
        export_json_to_excel(tHeader, data, fileName)
      })
    },
    formatJson (filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    /**
     * 获取参数枚举
     */
    queryStatic(type) {
      this.$api.okhttp({
        url: this.$http.adornUrl('/sys/sysstaticdata/getList'),
        method: 'get',
        params: this.$http.adornParams({
          'code': type ,
          "customerId":this.$util.cookies.get('customer_id')
        })
      }).then((data) => {
        if (data && data.code === 0) {
          this.meterTypeList = data.page
          this.dataForm.energyType = data.page[0].paramKey;
          this.unit = data.page[0].paramExt;

        } else {
          this.meterTypeList = []
        }
    });
    },
    initAlarmChart(opt,obj){
      let option={
          grid:{
            x:80,
            y:30,
            x2:55,
            y2:35,
          },
          title:{
              text:opt.title,
              show:true,
              left:'center',
              top:5,
              textStyle:{
                  color:"#ccc",
                  fontSize:14,
                  fontFamily:"MicrosoftYaHei",
                  lineHeight:14,
              },
              padding:0,
          },
          tooltip: {
            trigger: 'item',
            formatter: '{b}<br/>{c}'
          },
          legend:{
            right:80,
            top:-5,
            data:[{
              name:'当前值'
            }]
          },
          xAxis:{
              type:'category',
              data:opt.x,
              axisLine:{
                  lineStyle:{
                      color:"#2C73D2",
                      type:'solid',
                      width:0.5
                  },
              },
              axisLabel:{
                  color:"#ccc",
                  interval:0,
                  rotate:10,
                  fontSize :10,
              },
              axisTick: {
                show:false,
                alignWithLabel: true
              }
          },
          dataZoom: [{
              startValue: opt.x.length>0?opt.x[0]:'',
              endValue:opt.x.length>12?opt.x[11]:opt.x[opt.x.length-1],
          }, {
              type: 'inside'
          }],
          yAxis:{
              type:'value',
              name:'单位',
              //data:opt.y,
              axisLabel:{
                  color:"#ccc",
              },
              axisLine:{
                  lineStyle:{
                      color:"#ccc",
                      type:'soild',
                      opacity:0,
                  }
              },
              axisLabel:{
                  formatter:function(value,index){
                    return value;
                  }
              },
              axisTick: {
                  show:false,
                  alignWithLabel: true
              },
              splitLine:{
                  lineStyle:{
                      color:"#2C73D2",
                      type:"dotted",
                      opacity:0.5,
                  }
              },
          },
          series: [{
              name: '当前值',
              type: 'line',
              data: opt.data,
              itemStyle:{
              },
              lineStyle:{
                normal:{
                   color:"rgba(76,126,223)",
                }
              },
              markLine : {
                  symbol:"none",               //去掉警戒线最后面的箭头
                  label:{
                      position:"end",         //将警示值放在哪个位置，三个值“start”,"middle","end"  开始  中点 结束
                  },
                  lineStyle:{
                    normal:{
                      color:"rgb(245,108,108)",
                      type:"solid",
                    }
                  },
                  data : [{
                      silent:false,             //鼠标悬停事件  true没有，false有
                      lineStyle:{               //警戒线的样式  ，虚实  颜色
                          type:"solid",
                          color:"rgb(245,108,108)"
                      },
                      name: '上限',
                      yAxis: opt.up
                  },{
                      silent:false,             //鼠标悬停事件  true没有，false有
                      lineStyle:{               //警戒线的样式  ，虚实  颜色
                          type:"solid",
                          color:"rgb(245,108,108)"
                      },
                      name: '下限',
                      yAxis: opt.down
                  }]
              }
          }],
          //color:['#4C7EDF','#FFCC00', '#00CC33', '#D05454']
      }
   //   console.log(JSON.stringify(option));
      opt.chart = Echarts.init(document.getElementById(obj));
      opt.chart.setOption(option);
    },
    getAlarmDataList() {
      this.dataListLoading = true;
      this.$api.okhttp({
        url: this.$http.adornUrl('/ecs/ecsalarminfo/list'),
        method: 'get',
        params: this.$http.adornParams({
          'page': this.page.page,
          'limit': this.page.size,
          'projectId': this.$util.cookies.get("cuuren_projectId"),
          "customerId":this.$util.cookies.get('customer_id')
        })
      }) .then((data) => {
        if (data && data.code === 0) {
          this.alarmDataList=data.page.list;
          if(this.alarmDataList.length>0){
            this.$refs.alarmTable.setCurrentRow(this.alarmDataList[0]);
            this.getChartData(this.alarmDataList[0]);
          }
          this.page.total = data.page.totalCount;
        }
        else{
          this.alarmDataList=[];
          this.page.total = 0;
        }
        this.dataListLoading = false;
      });
    },
    clickRow(row){
      this.getChartData(row);
    },
    getChartData(row){
      this.dataListLoading1 = true
      this.businessChart.down = '';
      this.businessChart.up = '';
      this.businessChart.info = []
      this.$api.okhttp({
        url: this.$http.adornUrl(`/ecs/ecsalarminfo/info/`+row.alarmId),
        method: 'get',
        params: this.$http.adornParams({
          "customerId":this.$util.cookies.get('customer_id')
        }),
      }).then((data)=>{
        if (data && data.code == 0) {
          this.handleDataChart(data.ecsalarminfo);
        }

      }).finally(()=>{
        this.dataListLoading1 = false
      })
    },
    handleDataChart(ecsalarminfo){
      //处理返回的所有的数据
      this.businessChart={
          chart:"",
          x:[],
          data:[],
          title:""
      },
      this.businessChart.title=`告警详细`;
      this.businessChart.down = ecsalarminfo.quotaInfo.downVal;
      this.businessChart.up = ecsalarminfo.quotaInfo.upVal;
      this.businessChart.info = ecsalarminfo.info
      // ecsalarminfo.info.forEach((item,index)=>{
      //   //图表一
      //   this.businessChart.x.push(item.rtime);
      //   this.businessChart.data.push(item.oval);
      // })
      // this.initAlarmChart(this.businessChart,'businessAreaChart');
    },
    // 每页数
    sizeChangeHandle (val) {
      this.page.size = val;
      this.page.page = 1;
      this.getAlarmDataList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.page.page = val;
      this.getAlarmDataList()
    },
  },
  watch:{
    'dataForm.energyType':function(newV,oldV){
      this.unit = this.meterTypeList.find(item => item.paramKey == newV).paramExt;
    },
    'dataForm.dateType':function(newV,oldV){
        let str=''
        switch(newV){
          case 'date':
            str= Util.dateFormat('YYYY-mm-dd',new Date())
            break;
          case 'month':
            str=Util.dateFormat('YYYY-mm',new Date())
            break;
          case 'year':
            str=Util.dateFormat('YYYY',new Date())
            break;
        }
        this.dataForm.date=str;
    }
  }
};
</script>

<style scoped>

.tree-area { background-color: rgba(0, 0, 0, 0.1);
  width: 250px !important;
  /* box-shadow: 0px 0px 2px 2px #f7f6f6; */
  padding-top: 10px;
  padding-left: 15px;
}
.bg-white {
  box-shadow: 0px 0px 2px 2px #f7f6f6;
}
.el-tree-node__content {
  height: 30px !important;
}
.busi-chart{
    width: 100%;
    height: 250px;
    margin-top: 10x;
    margin-bottom: 20px;
}
.el-form-item{
  margin-bottom: 0px;
}
.search-area{
   display:flow-root;
   margin-bottom: 10px;
   border: 1px solid #e8e8e8;
   border-left: none;
   border-right: none;
   padding: 10px 0px 10px 0px;
}
</style>
